package xyz.zhzby.cyzx.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.acl.entity.Role;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.acl.service.IPermissionService;
import xyz.zhzby.cyzx.acl.service.IRoleService;
import xyz.zhzby.cyzx.acl.service.IUserService;
import xyz.zhzby.cyzx.acl.service.IndexService;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.exception.CommonErrorMessageEnum;
import xyz.zhzby.cyzx.servicebase.utils.CheckUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zby
 * @date 2021/12/07
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    public RestResponse<Map<String, Object>> getUserInfo() {
        //获取当前登录用户用户名
        User user = CyzxSecurityContextHolder.getSubject();
        Map<String, Object> result = new HashMap<>();
        CheckUtil.notNullThrowBusinessException(user, "", CommonErrorMessageEnum.DEFAULT);

        //根据用户id获取角色
        List<Role> roleList = roleService.selectRoleByUserId(user.getId());
        List<String> roleNameList = roleList.stream().map(Role::getName).collect(Collectors.toList());
        if (roleNameList.size() == 0) {
            //前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleNameList.add("");
        }

        //根据用户id获取操作权限值
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());

        result.put("id", user.getId());
        result.put("name", user.getNickName());
        result.put("avatar", user.getAvatar());
        result.put("roles", roleNameList);
        result.put("permissionValueList", permissionValueList);
        return RestResponse.success(result);
    }

    public List<JSONObject> getMenu(User user) {
        //根据用户id获取用户菜单权限
        return permissionService.selectPermissionByUserId(user.getId());
    }
}
